﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Diagnostics.Contracts;

namespace AnnotateMe.Interfaces
{
    public class CompositeShape : Shape
    {
        private readonly ReadOnlyCollection<Shape> shapes;

        public CompositeShape(IList<Shape> shapes)
        {
            Contract.Requires(shapes != null);

            this.shapes = new ReadOnlyCollection<Shape>(shapes);
        }

        public ReadOnlyCollection<Shape> Shapes { get { return this.shapes; } }

        public override void Draw()
        {
            foreach (var shape in this.Shapes)
            {
                shape.Draw();
            }
        }

        public override ImmutableRectangle GetContainingRectangle()
        {
            double x = 0, y = 0, xx = 0, yy = 0;
            bool initialized = false;
            foreach (var shape in this.Shapes)
            {
                var rect = shape.GetContainingRectangle();
                if (!initialized)
                {
                    x = rect.OriginPoint.X;
                    y = rect.OriginPoint.Y;
                    xx = x + rect.Size.Width;
                    yy = y + rect.Size.Height;
                    initialized = true;
                }
                else
                {
                    x = Math.Min(x, rect.OriginPoint.X);
                    y = Math.Min(y, rect.OriginPoint.Y);
                    xx = Math.Max(xx, rect.OriginPoint.X + rect.Size.Width);
                    yy = Math.Max(yy, rect.OriginPoint.Y + rect.Size.Height);
                }
            }

            return new ImmutableRectangle(new ImmutablePoint(x, y), new ImmutableSize(xx - x, yy - y), (_) => { });
        }

        public override Shape MoveBy(double deltaX, double deltaY)
        {
            return new CompositeShape(this.shapes.Select(shape => shape.MoveBy(deltaX, deltaY)).ToList());
        }
    }
}
